<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="roleType" label="角色类型">
          <el-radio-group v-model="listQuery.roleType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('RoleType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="roleCode" label="角色编码">
          <InputTagDialog v-model="listQuery.roleCode" placeholder="角色编码" title="填写角色编码" />
        </el-form-item>
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="listQuery.roleName" placeholder="角色名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('CommonEnableDisable')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <el-button v-show="checkAuthByCode('PD0015')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          <el-button v-show="checkAuthByCode('PD0018')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="角色类型" prop="roleType" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('RoleType')" :enum-key="row.roleType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色编码" prop="roleCode" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.roleCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" prop="roleName" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.roleName }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonEnableDisable')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('PD0016')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('PD0017')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-radio-group v-model="obj.roleType">
            <el-radio-button v-for="item in getEnumList('RoleType')" :label="item.key" :key="item.key">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="obj.roleCode" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="obj.roleName" placeholder="请输入角色名称，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-switch v-model="obj.state" active-value="1" active-text="启用" inactive-value="0" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
        <el-form-item label="权限" v-if="obj.roleType === '1'">
          <permissionTree v-model:checkedIdList="permissionIdCheckedList" @checkedTree="checkedPermission" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess, svc, initListUpdate} from "@/config/common";
import permissionTree from '@/views/components/base/permissionTree.vue'
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";

const emptyObj = {
  roleType: null, // 角色类型
  roleCode: null, // 角色编码
  roleName: null, // 角色名称
  state: '1', // 状态
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'role_nocache',
  mixins: [baseConfig],
  components: {
    InputTagDialog,
    permissionTree,
  },
  data() {
    return {
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        roleType: null,
        roleCode: null,
        roleName: null,
        state: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        roleType: [{ required: true, validator: customValidator, min: 0, max: 20, label: '角色类型', trigger: ['blur', 'change'] }],
        roleCode: [{ required: false, validator: customValidator, min: 0, max: 50, label: '角色编码', trigger: ['blur', 'change'] }],
        roleName: [{ required: true, validator: customValidator, min: 0, max: 200, label: '角色名称', trigger: ['blur', 'change'] }],
        state: [{ required: true, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
      },
      permissionIdCheckedList: [],
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.getList()
  },
  methods: {
    getListPageSize,
    getList() {
      this.listLoading = true
      doGet(svc, '/role/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.permissionIdCheckedList = []
      doGet(svc, '/role-permission/page', {roleId: row.id, pageSize: getListPageSize()}, false).then(res => {
        this.permissionIdCheckedList = res['records'].map(item => {
          return item.permissionId
        })
        this.dialogType = 'edit'
        this.dialogTypeTitle = '编辑'
        this.dialogVisible = true
        this.checkStrictly = true
        this.obj = Object.assign({}, row)
      })
    },
    handleView(row) {
      this.permissionIdCheckedList = []
      doGet(svc, '/role-permission/page', {roleId: row.id, pageSize: getListPageSize()}, false).then(res => {
        res['records'].map(item => {
          this.permissionIdCheckedList.push(item.permissionId)
        })
        this.dialogType = 'view'
        this.dialogTypeTitle = '详情'
        this.dialogVisible = true
        this.checkStrictly = false
        this.obj = Object.assign({}, row)
      })
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(svc, '/role/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(svc, '/role/' + row.id, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('roleList', '/role/page')
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.obj
      o.permissions = []
      this.permissionIdCheckedList.map(item => {
        if (item != null)
          o.permissions.push({permissionId: item})
      })
      doPost(svc, '/custom/saveRole', o).then(() => {
        notifySuccess('操作成功')
        this.getList()
        this.dialogVisible = false
        this.permissionIdCheckedList = []
        initListUpdate('roleList', '/role/page')
      })
    },
    checkedPermission(data) {
      if (data !== undefined) {
        this.permissionIdCheckedList = data;
      }
    },
  }
}
</script>
